//
//  AIGirlUserInfoTopicViewController.swift
//  AIGirl
//
//  Created by Rae on 2023/12/27.
//

import UIKit

class AIGirlUserInfoTopicViewController: AIGirlBaseViewController {

    private lazy var backButton = c_make_ex(UIButton.self)
        .image("AIGirl_Signin_back").end()
    private var sliderView = AIGirlMeansSliderView()
    private lazy var titleLabel = c_make_ex(UILabel.self)
        .color(.white).font(22.font_bold).alignment(.center)
        .text("Choose 5 tags you like").line(2).end()
    private lazy var doneButton = c_make_ex(AIGirlSubmitButton.self)
        .color(.white).font(21.font_bold).corner(20)
        .text("Done").end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var dataList:[AIGirlInterestModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData()
        
        view.subviews{
            backButton
            sliderView
            titleLabel
            collectionView
            doneButton
        }
        
        backButton.leading(15).top(.statusHeight).size(30)
        sliderView.leading(37.5).trailing(37.5).height(4.5)
        sliderView.Top == backButton.Bottom + 12
        titleLabel.leading(15).trailing(15)
        titleLabel.Top == sliderView.Bottom + 55
        doneButton.leading(37.5).trailing(37.5).height(50).bottom(60)
        collectionView.leading(0).trailing(0)
        collectionView.Top == titleLabel.Bottom + 25
        collectionView.Bottom == doneButton.Top - 25
        
        sliderView.value = 100
        let layout = UICollectionViewLeftAlignedLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.sectionInset = UIEdgeInsets(top: 0, left: 20.0, bottom: 0, right: 20.0)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlInterestItem.self, forCellWithReuseIdentifier: AIGirlInterestItem.description())
            v.showsVerticalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        doneButton.addTarget(self, action: #selector(clickDoneButton), for: .touchUpInside)
    }
    
    private func loadData(){
        ToastTool.show()
        DispatchQueue.main.asyncAfter(deadline: .now()+2) {
            if let userId = GlobalTool.userModel?.id {
                self.request.start(.interestsList(isPart: true, type: 1, userId: userId),type: AIGirlInterestModel.self) { result in
                    
                    if result.isSuccessful, let model = result.models {
                        self.dataList = model
                        self.collectionView.reloadData()
                    }
                }
            }
        }
        
    }
    
    @objc private func clickDoneButton(){
        
        var nameArr = [String]()
        var idArr = [String]()
        for model in dataList {
            if model.isSel {
                nameArr.append(model.name)
                idArr.append(String(model.id))
            }
        }
        if nameArr.count == 0 {
            "Please choose at least one topic that interests you!".toast_error
            return
        }
        let nameString = nameArr.joined(separator: ",")
        let idString = idArr.joined(separator: ",")
        request.start(.saveUserInterests(ids: idString)) { result in
            if result.isSuccessful {
                "Successful!".toast_success
                UserDefaultsManager.setInt(0, forKey: .currentPage)
                UserDefaultsManager.setInt(99, forKey: .isShowFirstAward)
                UserDefaultsManager.setBool(false, forKey: .isInChatRoom)
                self.navigationController?.pushViewController(AIGirlLoadingViewController(), animated: true)
            }
        }
    }
}

extension AIGirlUserInfoTopicViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlInterestItem.description(), for: indexPath) as? AIGirlInterestItem else { return UICollectionViewCell() }
        item.model = dataList[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var index = 0
        var model = dataList[indexPath.row]
        model.isSel = !model.isSel
        for md in dataList {
            if md.isSel {
                index += 1
            }
        }
        if index >= 5 && model.isSel {
            return
        }
        dataList[indexPath.row] = model
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let model = dataList[indexPath.row]
//        var w = model.name.caculateWidth(CGSize(width: 110, height: 40), 16.font_medium!)
        var w = (model.name as NSString).size(withAttributes: [NSAttributedString.Key.font: 16.font_medium!]).width
        w = w + 30.0
        return CGSize(width: w, height: 40)
    }
}
